const { db } = require("../../db/db2");

async function GetPinsList(req, res) {
  try {
    const { pageNum = 1, pageSize = 10 } = req.body; // 支持分页

    // 查询沸点列表数据
    const pinsQuery = `
      SELECT p.PinId, p.PinContent, p.UrlTitle, p.RealyUrl, p.ActivityId, p.CircleId, p.CircleTypeId, p.PublisherId,
      a.ActivityTitle, c.CircleTitle, ct.CircleTypeName, u.UserName,u.HeaderImg,u.SelfDescription,
      IFNULL(p.PublishTime,'') as PublishTime
      FROM Pin p left join Ativity a on p.ActivityId = a.ActivityId left join Circle c on p.CircleId = c.CircleId
      left join CircleType ct on p.CircleTypeId = ct.CircleTypeId left join User u on p.PublisherId = u.UserId
      ORDER BY PublishTime DESC
      LIMIT ?, ?
    `;

    // 查询结果的偏移量
    const offset = (pageNum - 1) * pageSize;

    const [pins] = await db.promise().query(pinsQuery, [offset, pageSize]);

    let pinsWithAttachments = [];

    if (pins.length > 0) {
      // 查询沸点对应的附件数据
      const attachmentQuery = `
 SELECT PinId, Url
 FROM PinAttachment
 WHERE PinId IN (?) AND IsValid=1
`;
      const pinIds = pins.map((pin) => pin.PinId); // 提取所有的 PinId

      const [attachments] = await db.promise().query(attachmentQuery, [pinIds]);

      // 将附件数据按照 PinId 分组
      const attachmentsByPinId = attachments.reduce((acc, attachment) => {
        if (!acc[attachment.PinId]) {
          acc[attachment.PinId] = [];
        }
        acc[attachment.PinId].push(attachment.Url);
        return acc;
      }, {});

      // 将附件数据添加到每个沸点
      pinsWithAttachments = pins.map((pin) => ({
        ...pin,
        Attachments: attachmentsByPinId[pin.PinId] || [],
      }));
    }

    // 返回结果
    res.send({
      status: 0,
      data: pinsWithAttachments,
      totalCount: pins.length, // 如果需要返回总数，或者可以通过分页查询来计算
    });
  } catch (err) {
    console.error("Error:", err);
    res.send({ Message: "查询数据失败", status: 1 });
  }
}

module.exports = { GetPinsList };
